package adv7.bank2;

import java.util.Random;

/**
 * @author oldliu
 * @since 1.0
 */
//取钱人
public class Taker extends Thread {
    private Account ac;

    public Taker(Account ac, String name) {
        super(name);
        this.ac = ac;
    }

    @Override
    public void run() {
        Random r = new Random();
        while (true) {
            int m = r.nextInt(200);
            System.out.println(super.getName() + "准备取钱" + m + "元，当前余额是：" + ac.getMoney() + "元");
            synchronized (ac) {
                while (ac.getMoney() < m) {
                    //钱不够
                    System.out.println(super.getName() + "取钱" + m + "元，当前余额是：" + ac.getMoney() + "元");
                    System.out.println(super.getName() + "钱不够，等待中");
                    try {
                        ac.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(super.getName() + "被唤醒，要取钱 " + m + "元，当前余额是：" + ac.getMoney() + "元");
                ac.withdraw(m);

            }
            System.out.println(super.getName() + "取钱" + m + "元，余额是：" + ac.getMoney() + "元");
        }
    }
}
